package juc.blockqueue.linkedblockdeque;

/**
 * @ClassName BidirectionalBuffer
 * @PackageName juc.blockqueue.linkedblockdeque
 * @projectName myThread
 * @Description 4. 双向缓冲队列
 * @Author games
 * @Date 2025/9/4 下午3:29
 * @Version 1.0
 */
import java.util.concurrent.LinkedBlockingDeque;

public class BidirectionalBuffer {
    /**
     * 主方法，演示使用LinkedBlockingDeque实现双端数据的生产者和消费者模式
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        // 创建一个容量为20的链表阻塞双端队列
        LinkedBlockingDeque<String> buffer = new LinkedBlockingDeque<>(20);

        // 前端数据源
        Thread frontSource = new Thread(() -> {
            try {
                for (int i = 1; i <= 5; i++) {
                    String data = "Front-Data-" + i;
                    buffer.putFirst(data);
                    System.out.println("前端添加: " + data);
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // 后端数据源
        Thread backSource = new Thread(() -> {
            try {
                for (int i = 1; i <= 5; i++) {
                    String data = "Back-Data-" + i;
                    buffer.putLast(data);
                    System.out.println("后端添加: " + data);
                    Thread.sleep(300);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // 前端处理器（从头部处理）
        Thread frontProcessor = new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    String data = buffer.takeFirst();
                    System.out.println("前端处理器处理: " + data);
                    Thread.sleep(400);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // 后端处理器（从尾部处理）
        Thread backProcessor = new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    String data = buffer.takeLast();
                    System.out.println("后端处理器处理: " + data);
                    Thread.sleep(600);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        frontSource.start();
        backSource.start();
        frontProcessor.start();
        backProcessor.start();
    }
}

